package com.xxxx.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.comment.constants.RedisConstants;
import com.xxxx.comment.entity.SeckillVoucher;
import com.xxxx.comment.entity.VoucherOrder;
import com.xxxx.comment.entity.dto.Result;
import com.xxxx.comment.mapper.SeckillVoucherMapper;
import com.xxxx.comment.mapper.VoucherMapper;
import com.xxxx.comment.mapper.VoucherOrderMapper;
import com.xxxx.comment.service.IVoucherOrderService;
import com.xxxx.comment.utils.RedisIdWorker;
import com.xxxx.comment.utils.SimpleRedisLock;
import com.xxxx.comment.utils.UserHolder;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务实现类
 *
 * @author 罗智锋
 * @since 2021-12-22
 */
@Service
@Transactional
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder>
        implements IVoucherOrderService, ApplicationContextAware {

    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private VoucherMapper voucherMapper;

    @Resource
    private VoucherOrderMapper voucherOrderMapper;

    private IVoucherOrderService proxy;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> addSeckillOrderScript;

    // 阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    // 异步处理线程池(单线程池，确保FIFO)
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void initMy() {
        log.warn("-----------------线程池添加订单处理Stream队列");
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandlerMy());
    }

    private class VoucherOrderHandlerMy implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    // 1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2.创建订单
                    handleVoucherOrder(voucherOrder);
                }catch (Exception e){
                    log.error("处理订单异常",e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        // redisson 的锁
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        // 获取锁
        boolean isLock = lock.tryLock();
        // 判断是否获取锁成功
        if(!isLock){
            // 获取锁失败,返回错误或重试
            log.error("不允许重复下单");
        }
        try {
            // 获取代理对象 (事务)
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            proxy.createVoucherOrderOld1(voucherOrder);
        }finally {
            lock.unlock();
        }
    }

    private ApplicationContext context;

    public void setApplicationContext(ApplicationContext context) {
        this.context = context;
    }

    @PostConstruct
    private void init() {
        log.warn("-----------------线程池添加订单处理Stream队列");
        SECKILL_ORDER_EXECUTOR.execute(new VoucherOrderHandler());
    }

    static {
        addSeckillOrderScript = new DefaultRedisScript<>();
        addSeckillOrderScript.setLocation(new ClassPathResource("/lua/7.6addSeckillOrder.lua"));
        addSeckillOrderScript.setResultType(Long.class);
    }

    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            proxy = context.getBean(IVoucherOrderService.class);
            log.warn("线程池启动，从消息队列中获取订单");
            while (true) {
                MapRecord<String, Object, Object> record;
                try {
                    // 1、获取stream队列中的订单信息XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1
                    List<MapRecord<String, Object, Object>> orderList = stringRedisTemplate.opsForStream().read(
                            // 注定消费者组g1中的c1去消费内容
                            Consumer.from("g1", "c1"),
                            // 指定消费的每次读取一条新消息，并且队列为空时，则阻塞2秒，直到收到新的消息或超时终止
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            // 指定读取最新的消息
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed()));
                    // 2、判断订单信息是否为空,如果为null,说明没有消息，继续下一次循环
                    // log.error("Stream队列中的订单列表：[{}]", orderList);
                    if (orderList == null || orderList.isEmpty()) {
                        continue;
                    }
                    // 3、解析数据
                    record = orderList.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 4、创建订单
                    proxy.createVoucherOrder(voucherOrder);
                    // 5、向队列确认已消费该条消息 XACK s1 g1
                    stringRedisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
                } catch (Exception e) {
                    handlePendingList();
                    log.error("消息队列处理用户[{}]抢购优惠券异常{}", UserHolder.getUser().getId(), e.toString());
                }
            }
        }

        public void handlePendingList() {
            while (true) {
                try {
                    // 1、获取pending-list中的订单信息 XREADGROUP GROUP group consumer STREAMS key id
                    // 为什么这里的ReadOffset.from("0")是0？因为这个方法就是专门用于处理等待队列中的
                    // 正常来说，在while循环里正常处理订单都不会进入这个函数，就是因为在while循环中异常，导致这笔订单进入等待队列
                    List<MapRecord<String, Object, Object>> records = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.from("0")));
                    // 2、判断订单信息是否为空，为空则没有消息，结束该方法（因为该方法是处理pending-list的）
                    if (records == null || records.isEmpty()) {
                        break;
                    }
                    // 3、解析数据，并创建订单
                    MapRecord<String, Object, Object> record = records.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    proxy.createVoucherOrder(voucherOrder);
                    // 4、确认消息
                    stringRedisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pending-list订单异常{}", e.toString());
                }
            }
        }

    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        Long orderId = redisIdWorker.nextId(RedisConstants.SECKILL_ORDER_BUSINESS_NAME);
        // 1、执行lua脚本
        Long result = stringRedisTemplate.execute(addSeckillOrderScript, Collections.emptyList(),
                voucherId.toString(), userId.toString(), orderId.toString(),
                RedisConstants.SECKILL_STOCK_KEY, RedisConstants.SECKILL_ORDER_KEY);
        log.warn("redis中查询优惠券[{}]是否有库存或用户[{}]是否重复下单 ==> result:[{}]", voucherId, userId, result);
        // 2、判断结果是否为0，不为0，代表没有“尝试”购买的资格
        if (result != null && result != 0)
            return Result.fail(result == 1 ? "库存不足" : "不能重复下单");
        // 3、result为0，证明redis中没有锁，代表有“尝试”购买优惠券的资格
        // 返回订单ID
        return Result.ok(orderId);
    }

    public Result seckillVoucherMy(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        Long orderId = redisIdWorker.nextId(RedisConstants.SECKILL_ORDER_BUSINESS_NAME);
        // 1、执行lua脚本
        Long result = stringRedisTemplate.execute(addSeckillOrderScript, Collections.emptyList(),
                voucherId.toString(), userId.toString(), orderId.toString(),
                RedisConstants.SECKILL_STOCK_KEY, RedisConstants.SECKILL_ORDER_KEY);
        log.warn("redis中查询优惠券[{}]是否有库存或用户[{}]是否重复下单 ==> result:[{}]", voucherId, userId, result);
        // 2、判断结果是否为0，不为0，代表没有“尝试”购买的资格
        if (result != null && result != 0)
            return Result.fail(result == 1 ? "库存不足" : "不能重复下单");
        // 3、result为0，证明redis中没有锁，代表有“尝试”购买优惠券的资格
        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 生成订单id
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        // 代金券id
        voucherOrder.setVoucherId(voucherId);
        // 保存到阻塞队列
        orderTasks.add(voucherOrder);
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 返回订单ID
        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        // 创建锁对象
        RLock rLock = redissonClient.getLock(RedisConstants.LOCK_SECKILL_ORDER_KEY + userId);
        // 尝试获取锁
        boolean isLock = rLock.tryLock();
        if (!isLock) { // 获取锁失败
            log.error("不允许重复下单！");
            return;
        }
        try {
            // 5、查询订单
            if (voucherOrderMapper.getVoucherOrderRec(userId, voucherId) != 0) {
                log.error("用户[{}]已抢购过优惠券[{}]", userId, voucherId);
                return;
            }
            // 6 扣减库存
            Boolean isSuccess = voucherMapper.updateSeckillVoucher(voucherId);
            if (!isSuccess) {
                // 扣减库存失败
                log.error("用户[{}]抢购优惠券[{}]失败，库存不足！", userId, voucherId);
                return;
            }
            if (!save(voucherOrder)) {
                log.error("用户[{}]抢购优惠券[{}]失败，系统错误！", userId, voucherId);
            }
        } finally {
            rLock.unlock();
        }
    }

    // 旧的秒杀券方法
    @Override
    public Result seckillVoucherOld(Long voucherId) {
        SeckillVoucher voucher = seckillVoucherMapper.selectById(voucherId);
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始");
        }
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        // 判断库存是否充足
        if(voucher.getStock() < 1){
            return Result.fail("库存不足");
        }
        // 关键 ----> 一人一单
        Long userId = UserHolder.getUser().getId();
        synchronized (userId.toString().intern()){
            // 获取代理对象 (事务)
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrderOld(voucherId);
        }
    }
    /**
     *  1.此处锁必须加在事务外面,避免事务未提交,锁已经释放,其它线程进入
     *  2.@Transactional注解的事务是由其代理对象生效的,
     *    其它方法再调用这个方法时 proxy.createVoucherOrderOld(voucherId) 应该用其代理类调用
     */
    @Transactional(rollbackFor = Exception.class)
    public Result createVoucherOrderOld(Long voucherId){
        // 关键 ----> 一人一单
        Long userId = UserHolder.getUser().getId();
        // 查询订单
        Long count = lambdaQuery()
                .eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucherId)
                .count();
        if(count > 0){
            return Result.fail("用户已经购买过了");
        }

        // 扣减库存
        UpdateWrapper<SeckillVoucher> wrapper = new UpdateWrapper<>();
        // 乐观锁  --- mysql有行锁,只能有一个线程修改
        wrapper.setSql("stock = stock - 1")
                .eq("voucher_id",voucherId)
                .gt("stock",0);
        int update = seckillVoucherMapper.update(wrapper);
        if(update < 1){
            return Result.fail("库存不足");
        }

        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 生成订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        // 代金券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        return Result.ok(orderId);
    }

    // 新的秒杀券方法 --- 分布式锁
    @Override
    public Result seckillVoucherNew(Long voucherId) {
        SeckillVoucher voucher = seckillVoucherMapper.selectById(voucherId);
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始");
        }
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        // 判断库存是否充足
        if(voucher.getStock() < 1){
            return Result.fail("库存不足");
        }
        // 关键 ----> 一人一单
        Long userId = UserHolder.getUser().getId();

        // 创建锁对象  setNx
       // SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);

        // redisson 的锁
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        // 获取锁
        boolean isLock = lock.tryLock();
        // 判断是否获取锁成功
        if(!isLock){
            // 获取锁失败,返回错误或重试
            return Result.fail("不允许重复下单");
        }
        try {
            // 获取代理对象 (事务)
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrderOld(voucherId);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void createVoucherOrderOld1(VoucherOrder voucherOrder) {
        // 关键 ----> 一人一单
        Long userId = voucherOrder.getUserId();
        // 查询订单
        Long count = lambdaQuery()
                .eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucherOrder.getVoucherId())
                .count();
        if(count > 0){
            log.error("用户已经购买过了");
        }

        // 扣减库存
        UpdateWrapper<SeckillVoucher> wrapper = new UpdateWrapper<>();
        // 乐观锁  --- mysql有行锁,只能有一个线程修改
        wrapper.setSql("stock = stock - 1")
                .eq("voucher_id",voucherOrder.getVoucherId())
                .gt("stock",0);
        int update = seckillVoucherMapper.update(wrapper);
        if(update < 1){
            log.error("库存不足");
        }
        save(voucherOrder);
    }

}
